package com.atgion.gateway.filter;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.atgion.exception.exception.GlobalException;
import com.atgion.gateway.utis.JwtTokenUtil;
import com.atgion.spzx.model.vo.base.Result;
import com.atgion.spzx.model.vo.base.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.List;

//过滤器
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();  //路径匹配

    //    过滤器
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest(); //获取请求对象
        String path = request.getURI().getPath();  //获取请求的URI路径。用于匹配路径
        if(antPathMatcher.match("/api/**/auth/**", path)) {
            String userInfo = this.doFilterInternal(request);// getUserInfo自定义方法
            if(null == userInfo) {
//                ServerHttpResponse response = exchange.getResponse();
                throw new GlobalException(ResultCode.LOGIN_AUTH);
//                return out(response, ResultCode.LOGIN_AUTH);
            }
        }
        return chain.filter(exchange);
    }


    //     返回 工具方法
    private Mono<Void> out(ServerHttpResponse response, ResultCode resultCodeEnum) {
        Result result = Result.success( resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");  //只过滤 获取用户数据
        return response.writeWith(Mono.just(buffer));
    }
    @Override
    public int getOrder() {
        return 0;
    }

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    protected String doFilterInternal(ServerHttpRequest request){
        String token = "";
        List<String> authHeader = request.getHeaders().get(jwtTokenUtil.getTokenHeader()); //获取请求头中的token
        if(null  != authHeader) {
            token = authHeader.get(0);  //取出token
        }
        if(!StringUtils.isEmpty(token)) {
            String userName = jwtTokenUtil.getUserNameFromToken(token);
            if(StringUtils.isEmpty(userName)) {
                return null ;
            }else {
                return userName; //将字符串转为对象
            }
        }
        return null;
    }


}

